//
//  oauthViewController.swift
//  MicroBlog
//
//  Created by QT on 15/7/29.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit
import SVProgressHUD
class oauthViewController: UIViewController,UIWebViewDelegate{
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthURL()))
//
        
        
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
         SVProgressHUD.dismiss()
    }

    // 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
//        print("startLoad")
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
//        print("finishLoad")
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//    print("LoadWithRequest")
        let urlString = request.URL!.absoluteString
        
//        print(urlString)
        
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUri){
            return true
        }
        
        if let query = request.URL?.query where query.hasPrefix("code="){
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
//             print("https://api.weibo.com/2/comments/show_batch.json?access_token=\(code)")
            // TODO: 换取token
            getAccessToken(code)
//            close()
        }else{
            close()
        }

        return false
    }
    
    private func getAccessToken(code: String){
        NetWorkTools.sharedTools.getAccessToken(code) { (result, error) -> () in
            if result == nil || error != nil{
                print("网络不给力")
               
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                
            }
            else{
                let account = UserAccount(dict: result!)
                //
                ////                // 归档
                account.saveAccount()
                // 获取用户信息（包含name,avatar_large）
                UserAccount(dict: result!).loadUserInof()
                // 通知AppDelegate切换到welcome
                NSNotificationCenter.defaultCenter().postNotificationName(ViewControllerNotification, object: false)
////                print("登录成功监听")
                self.close()
            }
        }
    }

}
